﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MethodWorx.CMS.Plugins;

namespace MethodWorx.CMS.Workflow.Validate
{
    public class ValidateWorkflowComponent : WorkflowComponent<ValidateConfigurationController>
    {
        public ValidateWorkflowComponent(Plugin plugin)
            : base(plugin)
        {
        }

        public static Guid ComponentId = Guid.Parse("{F5694E7F-41A3-4D5D-833D-FE77DEFC9AB4}");

        public override Guid Id
        {
            get { return ComponentId; }
        }

        public override string Category
        {
            get { return "Input"; }
        }

        public override string Name
        {
            get { return "Validate"; }
        }

        public override string Description
        {
            get { return "Validates Workflow Input e.g Request Values"; }
        }

        public override string View
        {
            get { return "ValidateConfigurationView.ascx";  }
        }

        public override StepExecutionResult Execute(IWorkflowExecutionContext context, IWorkflowConfiguration configuration)
        {
            var validateConfig = configuration as ValidateConfiguration;
            var value = context.GetWorkflowValue(validateConfig.FieldName.TrimStart('{').TrimEnd('}'));
            
            //
            //  check required
            if(validateConfig.Required && (value == null || string.IsNullOrEmpty(value.ToString())))
                context.AddWorkflowError(validateConfig.FieldName.TrimStart('{').TrimEnd('}'), validateConfig.ErrorMessage);

            if(!string.IsNullOrEmpty(validateConfig.CompareWith) && !string.IsNullOrEmpty(validateConfig.ComparisonOption))
            {
                var otherValue = context.GetWorkflowValue(validateConfig.CompareWith.TrimStart('{').TrimEnd('}'));
                switch(validateConfig.ComparisonOption.ToLower())
                {
                    case "equals":
                        if(value.ToString() != otherValue.ToString())
                            context.AddWorkflowError(validateConfig.FieldName.TrimStart('{').TrimEnd('}'), validateConfig.ErrorMessage);
                        break;
                }
            }

            return StepExecutionResult.Ok();
        }
    }
}
